package cn.com.xinjinfu.pdoulcProduct.activity.recharge;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.ActTransactionDetailed;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseWebActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.user.ActCertification;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.ActRechargeBean;
import cn.com.xinjinfu.pdoulcProduct.entity.BanksCardBean;
import cn.com.xinjinfu.pdoulcProduct.entity.BanksCardBean.SupportBanks;
import cn.com.xinjinfu.pdoulcProduct.entity.BuyActivityBean;
import cn.com.xinjinfu.pdoulcProduct.entity.FixedBuySuccessBean;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.BankImgUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.EditTextUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.LoginRequestUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.NewUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.ReloadUserInfo;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.BaseHelper;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.Constants;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.MobileSecurePayer;
import cn.com.xinjinfu.pdoulcProduct.view.AddAndSubView;
import cn.com.xinjinfu.pdoulcProduct.view.LoadStatusBox;

import static cn.com.xinjinfu.pdoulcProduct.entity.ActRechargeBean.*;

/**
 * 定期 转让 购买页面
 * Created by android-adt on 2015/12/30.
 */
public class BuyActivity extends BaseActivity implements OnClickListener, OnItemClickListener {
    protected static final String TAG = "CurrentFinancaialBuy";
    private Button mMffirmBuy;
    private LinearLayout rl_fixed_top, rl_transfor_top, ll_nomoney_bank, mNoMoneyHint, shouyi_yuSuan;
    private RelativeLayout rl_select_number, rl_account_num, select_voucher;
    private RelativeLayout ll_fixed_buy, ll_transfer_buy, transfer_all_nomey;
    private EditText mBetting_money, tv_carnum;
    private TextView all_fenshu, tv_fenshu, money_of_one, tv_account_balance, all_buy_money0, tv_rexharge_money, tv_rexharge_money0, ketou_money, tv_error_hint, tv_bank_name,
            tv_bankcart_num, tv_xian_e_info, shengyu_fenshu, mBankcart, tv_bank_hint, tv_shouyi, tv_quan_num, fuwuxieyi, jiekuanxieyi;
    private ListView lv;
    private PopupWindow pw;
    private BankCartAdapter adapter;
    private String Id, titlename,xiane;
    private double shengyuketou, transfer_mTouMoney, apr, mtouMoney, canUseingMoney, rate;

    private AddAndSubView add_and_sub;
    //银行图标，名称和卡号
    private String mBank, mBankCode;
    private SupportBanks supportBanks;

    private ImageView img_bankcard;
    private int objBuy, repaymentId, periodUnit, period, itemAmount, itemId, type;
    private int y, z;
    private User user;
    private RequestQueue requen;
    private List<SupportBanks> banksList;
    private FixedBuySuccessBean successBean;
    private BuyActivityBean buyBean;
    private ImageView iv_selector;
    private CheckBox cb;
    private Dialog dg;
    private BigDecimal bd;
    private String buyAmount = "0", bidType;

    private boolean isYuOrpay;
    /**
     * buyBoolean 默认为false，用于初始化页面数据；
     * 为true时，在点击确认按钮时，刷新页面数据，要判断返回结果中的stye 是否可以购买。
     * （关于为什么要更新页面数据问题：因为页面数据刷新快，防止用户在浏览购买页期间，
     * 出现数据变更而无法购买的问题，所以要在点击购买按钮时要刷新页面数据，判断是否可以购买）
     * ————————————————————————你明白了吗？——————————————————————————————
     */
    private boolean buyBoolean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_buy);
        ActivityManager.getInstance().addActivity(this);     //加入Activity管理
        user = AccountManager.getInstance().getUser();
        requen = Volley.newRequestQueue(this);
        Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();
        objBuy = bundle.getInt("objBuy");                   //判断是转让详情页（2）或定期页（1）跳转过来的
        Id = bundle.getString("Id");                        //标的id
        titlename = bundle.getString("titlename");          //标的名称
        xiane = bundle.getString("xiane");                  //标的名称
        TitleManager.showTitleWhite(BuyActivity.this, titlename, "");
        initView();
        initViewData();
        initOnChangeListener();
//        if (objBuy == 1) {                                   //初始化不同数据
//            loginThisRequest("bidId", "1211");
//        } else {
//            loginThisRequest("investTransferId", "1212");
//        }
        if (objBuy == 2) {
            loginThisRequest("investTransferId", "1212");//初始化不同数据
        } else {
            loginThisRequest("bidId", "1211");
        }
    }

    private void initView() {
        rl_fixed_top = (LinearLayout) findViewById(R.id.rl_fixed_top);
        rl_transfor_top = (LinearLayout) findViewById(R.id.rl_transfor_top);
        select_voucher = (RelativeLayout) findViewById(R.id.select_voucher);
        select_voucher.setOnClickListener(this);
        ll_fixed_buy = (RelativeLayout) findViewById(R.id.ll_fixed_buy);
        ll_transfer_buy = (RelativeLayout) findViewById(R.id.ll_transfer_buy);
        /*******收益预算*********/
        shouyi_yuSuan = (LinearLayout) findViewById(R.id.shouyi_yuSuan);
        /******错误信息提示******/
        tv_error_hint = (TextView) findViewById(R.id.tv_error_hint);
        //预期收益
        tv_shouyi = (TextView) findViewById(R.id.tv_shouyi);
        //剩余可投
        ketou_money = (TextView) findViewById(R.id.ketou_money);
        shengyu_fenshu = (TextView) findViewById(R.id.shengyu_fenshu);
        //转让剩余分数
        all_fenshu = (TextView) findViewById(R.id.all_fenshu);
        //可用余额
        tv_account_balance = (TextView) findViewById(R.id.tv_account_balance);
        //定期要投的金额
        mBetting_money = (EditText) findViewById(R.id.et_betting_money);
        mBetting_money.addTextChangedListener(mTextWatcher);
        //定期购买分数
        tv_fenshu = (TextView) findViewById(R.id.tv_fenshu);
        //转让每份价格、、、要购买分数
        money_of_one = (TextView) findViewById(R.id.money_of_one);
        all_buy_money0 = (TextView) findViewById(R.id.all_buy_money0);
        add_and_sub = (AddAndSubView) findViewById(R.id.add_and_sub);
        add_and_sub.setTextSize(19);
        add_and_sub.setButtonLayoutParm(50, 50);
        //协议
        tv_quan_num = (TextView) findViewById(R.id.tv_quan_num);
        fuwuxieyi = (TextView) findViewById(R.id.fuwuxieyi);
        jiekuanxieyi = (TextView) findViewById(R.id.jiekuanxieyi);
        fuwuxieyi.setOnClickListener(this);
        jiekuanxieyi.setOnClickListener(this);

        mMffirmBuy = (Button) findViewById(R.id.affirm_buy);
        mMffirmBuy.setOnClickListener(this);
        /**
         * 银行卡 布局
         */
        //银行未绑定
        mNoMoneyHint = (LinearLayout) findViewById(R.id.ll_nomoney_hint);
        //选择银行
        rl_select_number = (RelativeLayout) findViewById(R.id.rl_select_number);
        rl_select_number.setOnClickListener(this);
        //银行
        mBankcart = (TextView) findViewById(R.id.tv_bankcart);
        //限额提示
        tv_bank_hint = (TextView) findViewById(R.id.tv_bank_hint);
        //输入卡号
        rl_account_num = (RelativeLayout) findViewById(R.id.rl_account_num);
        tv_carnum = (EditText) findViewById(R.id.tv_carnum);
        //绑定过的
        ll_nomoney_bank = (LinearLayout) findViewById(R.id.ll_nomoney_bank);
        tv_bank_name = (TextView) findViewById(R.id.tv_bank_name);
        tv_bankcart_num = (TextView) findViewById(R.id.tv_bankcart_num);
        tv_xian_e_info = (TextView) findViewById(R.id.tv_xian_e_info);
        img_bankcard = (ImageView) findViewById(R.id.img_bankcard);

        //余额不足时，要从银行卡买入的差价金额
        tv_rexharge_money = (TextView) findViewById(R.id.tv_rexharge_money);
        tv_rexharge_money0 = (TextView) findViewById(R.id.tv_rexharge_money0);
        iv_selector = (ImageView) findViewById(R.id.iv_selector);
        cb = (CheckBox) findViewById(R.id.cb);
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    iv_selector.setImageResource(R.drawable.btn_ok);
                    mMffirmBuy.setEnabled(true);
                } else {
                    iv_selector.setImageResource(R.drawable.btn_no);
                    mMffirmBuy.setEnabled(false);
                }
            }
        });
        cb.setChecked(false);
    }

    private void initViewData() {
        if (objBuy == 0){
            select_voucher.setVisibility(View.GONE); //隐藏兜券

            rl_fixed_top.setVisibility(View.VISIBLE);
            ll_fixed_buy.setVisibility(View.VISIBLE);
            rl_transfor_top.setVisibility(View.GONE);
            ll_transfer_buy.setVisibility(View.GONE);
            mMffirmBuy.setEnabled(false);
        } else if (objBuy == 1) {
            rl_fixed_top.setVisibility(View.VISIBLE);
            ll_fixed_buy.setVisibility(View.VISIBLE);
            rl_transfor_top.setVisibility(View.GONE);
            ll_transfer_buy.setVisibility(View.GONE);
            mMffirmBuy.setEnabled(false);
        } else {
            rl_fixed_top.setVisibility(View.GONE);
            ll_fixed_buy.setVisibility(View.GONE);
            rl_transfor_top.setVisibility(View.VISIBLE);
            ll_transfer_buy.setVisibility(View.VISIBLE);
            mMffirmBuy.setEnabled(true);
        }
        showHaveBank();
    }

    private void initOnChangeListener() {
        //设置监听转让EditText内数值变化
        add_and_sub.setOnNumChangeListener(new AddAndSubView.OnNumChangeListener() {
            @Override
            public void onNumChange(View view, int num) {
                if (buyBean != null) {
                    itemAmount = 0;
                    itemId = 0;
                    type = 0;
                    rate = 0;
                    tv_quan_num.setText("");    //一旦改变购买金额，就置空优惠券
                    if (num > 0) {
                        tv_shouyi.setText(TextViewUtil.getSumLength(num * buyBean.getExpectInterest()));
                        all_buy_money0.setText(TextViewUtil.getSumLength(num * buyBean.getPortionTransferAmount()));
                        if (num > buyBean.getHavePortionNums()) {
                            ToastManager.showShort(BuyActivity.this, "最高可投不能超过剩余可投分数！");
                            add_and_sub.setNum(buyBean.getHavePortionNums());
                            tv_shouyi.setText(TextViewUtil.getSumLength(buyBean.getHavePortionNums() * buyBean.getExpectInterest()));
                            all_buy_money0.setText(TextViewUtil.getSumLength(buyBean.getHavePortionNums() * buyBean.getPortionTransferAmount()));
                        }
                    } else {
                        //置空份数时，默认一份显示
                        tv_shouyi.setText(TextViewUtil.getSumLength(buyBean.getExpectInterest()));
                        all_buy_money0.setText(TextViewUtil.getSumLength(buyBean.getPortionTransferAmount()));
                    }
                    /**
                     * 这几行是专门处理：刚好 余额==购买金额 的情况，因精度问题 （0.0000000003的精度）会弹出银行卡（虽然充值金额为0，但还是弹出了）
                     *———————————————— 对此我很无语，只能强制截取两位小数
                     */
                    transfer_mTouMoney = add_and_sub.getNum() * buyBean.getPortionTransferAmount();
                    bd = new BigDecimal(transfer_mTouMoney);
                    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                    transfer_mTouMoney = bd.doubleValue();
                    compareMoney(transfer_mTouMoney, canUseingMoney);
                }
            }
        });
    }

    /**
     * 绑定过的银行卡的展示
     */
    public void showHaveBank() {
        user = AccountManager.getInstance().getUser();
        if (user != null) {
            if (user.getBank() == -1) {
                tv_bank_name.setText(user.getBank_name());
                String id = user.getAccount();
                String show_id = "**** **** **** " + id.substring(id.length() - 4);
                tv_bankcart_num.setText(show_id);
                img_bankcard.setImageResource(new BankImgUtils().mBank(false, user.getBank_code()));
                if (user.getBank_status().equals("0")) {
                    tv_xian_e_info.setText("*每笔限额" + NumberFormat.getInstance().format(user.getSingle_amt() / 10000) +
                            "万元，每日限额" + NumberFormat.getInstance().format(user.getDay_amt() / 10000) + "万元");
                } else {
                    tv_xian_e_info.setText(user.getBank_name()+"维护中，暂无法支付\n可在PC端以网银充值方式进行支付");
                }
            }
        }
    }

    /**
     * 从选择优惠券界面返回到购买页
     * ——————————————————处理选择优惠券
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            itemId = data.getIntExtra("itemId", 0);
            itemAmount = data.getIntExtra("itemAmount", 0);
            type = data.getIntExtra("type", 0);
            rate = data.getDoubleExtra("rate", 0);
            if (itemId > 0) {
                if (type == 1) {
                    tv_quan_num.setText(rate + "%加息券");
                } else {
                    tv_quan_num.setText(itemAmount + "元兜券");
                }
                tv_quan_num.setTextColor(0xFFF4B942);
            } else {
                tv_quan_num.setText("选择兜券");
                mtouMoney = EditTextUtil.getDoubleEditText(mBetting_money);
                if (mtouMoney == 0) {
                    tv_quan_num.setTextColor(0xff666666);
                } else {
                    tv_quan_num.setTextColor(0xff6ED3D6);
                }
            }

            if (objBuy == 1 || objBuy == 0) {
                compareMoney(mtouMoney, canUseingMoney + itemAmount);
                if ((mtouMoney - itemAmount) <= 0) {
                    all_buy_money0.setText("0.00");
                } else {
                    all_buy_money0.setText(TextViewUtil.getSumLength(mtouMoney - itemAmount));
                }
            } else {
                compareMoney(transfer_mTouMoney, canUseingMoney + itemAmount);
                all_buy_money0.setText(TextViewUtil.getSumLength(add_and_sub.getNum() * buyBean.getPortionTransferAmount() - itemAmount));
            }
        }
    }

    /**
     * 更新页面数据
     */
    public void upData() {
        canUseingMoney = buyBean.getBalance();
        tv_account_balance.setText(TextViewUtil.getSumLength(canUseingMoney));
        if (objBuy == 0){
            //定期剩余可投的金额
            shengyuketou = buyBean.getBid().getAmount() - buyBean.getBid().getHasInvestedAmount();
            ketou_money.setText(TextViewUtil.getSumLength(shengyuketou));
            shengyu_fenshu.setTextColor(0xFFFFDA00);
            shengyu_fenshu.setText("单笔投资上限 " + xiane + " 元");
            //计算收益需要用到的数据
            repaymentId = buyBean.getBid().getRepayment().getId();
            apr = buyBean.getBid().getApr();
            periodUnit = buyBean.getBid().getPeriodUnit();
            period = buyBean.getBid().getPeriod();
        }else if (objBuy == 1) {
            //定期剩余可投的金额
            shengyuketou = buyBean.getBid().getAmount() - buyBean.getBid().getHasInvestedAmount();
            ketou_money.setText(TextViewUtil.getSumLength(shengyuketou));
            shengyu_fenshu.setText((int) (shengyuketou / 100) + " 份");
            //计算收益需要用到的数据
            repaymentId = buyBean.getBid().getRepayment().getId();
            apr = buyBean.getBid().getApr();
            periodUnit = buyBean.getBid().getPeriodUnit();
            period = buyBean.getBid().getPeriod();
        } else {
            //转让购买的初始化展示（1份）
            transfer_mTouMoney = add_and_sub.getNum() * buyBean.getPortionTransferAmount();
            bd = new BigDecimal(transfer_mTouMoney);
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            transfer_mTouMoney = bd.doubleValue();
            all_fenshu.setText(buyBean.getHavePortionNums() + "");
            money_of_one.setText(TextViewUtil.getSumLength(buyBean.getPortionTransferAmount()) + "  /份");
            tv_shouyi.setText(TextViewUtil.getSumLength(add_and_sub.getNum() * buyBean.getExpectInterest()));
            all_buy_money0.setText(TextViewUtil.getSumLength(transfer_mTouMoney));
            compareMoney(transfer_mTouMoney, canUseingMoney);
        }
    }


    /**
     * 页面初始化网络请求 (购买前 需要先 再次调用来判断是否可以购买)
     */
    private void loginThisRequest(String urlId, String OPT) {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        final Map<String, String> parameters = DataHandler.getParameters(OPT);
        if (user != null) {
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put(urlId, Id);
        }
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedThisRequest, error);
        request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requen.add(request);
    }

    private Response.Listener<JSONObject> succeedThisRequest = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            buyBean = JSON.parseObject(jobj.toString(), BuyActivityBean.class);
            dg.dismiss();
            if (JSONManager.getError(jobj) == -1) {
                initData();
            } else {
                ToastManager.showShort(BuyActivity.this, JSONManager.getMsg(jobj));
            }
        }
    };

    /**
     * 初始化页面数据后的选择：
     * buyBoolean true  就走继续购买流程
     *            false 只是单纯的初始化页面数据
     */
    protected void initData() {
        user = AccountManager.getInstance().getUser();
        if (buyBoolean) {                   //用来判断是页面初始化，还是判断购买状态
            if (objBuy == 1||objBuy == 0) {              //定期，首投
                shengyuketou = buyBean.getBid().getAmount() - buyBean.getBid().getHasInvestedAmount();
                if (shengyuketou > 0) {                                 //有剩余可投，可以购买
                    selectBuyTyleRequest(mtouMoney, canUseingMoney + itemAmount);
                } else {
                    allSoldOutDialog("理财产品");                       // "该理财产品已售空"
                }
            } else {             //转让
                if (buyBean.getTransferStatus() == 2) {    //判断是否可以购买
                    selectBuyTyleRequest(transfer_mTouMoney, canUseingMoney + itemAmount);
                } else {
                    allSoldOutDialog("他人转让");       // "该理财产品已售空"
                }
            }
        } else { upData(); }                           //初始化页面数据
    }

    /**
     * //判断是否设置过交易密码
     */
    public void setPayPWD(){
            if (user.getCurrUser().isSetPayPwd()) {
                PayPwdDilog mPayPwdDilog = new PayPwdDilog(this, null);
                mPayPwdDilog.setSuccessListener(new PayPwdDilog.SuccessListener() {
                    @Override
                    public void onPwdSuccess(String password) {
                        rechargeLoginRequest(password);
                    }
                });
            } else {
                Intent intent = new Intent();
                intent.putExtra("falg", 0);
                intent.setClass(this, TradePWD.class);        //跳转到支付密码设置页
                startActivity(intent);
            }
    }

    /**
     * 售空的Dialog
     *
     * @param info
     */
    public void allSoldOutDialog(String info) {
        UIManager.allSoldOutDialog(this, info, "确认", new OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManager.getInstance().exitActivity();
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (!NewUtil.checkClick(v.getId())) return;
        String url;
        Intent intent = new Intent(this, BaseWebActivity.class);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.affirm_buy:       //确定键
                buyBoolean = true;     //改变状态，说明接下来的请求不是初始化页面用，是为了判断是否可以购买
                if (isYuOrpay && user != null && user.getBank()==-1 && user.getBank_status().equals("2")) {
                    Toast.makeText(mContext, user.getBank_name()+"维护中，暂无法支付\n可在PC端以网银充值方式进行支付", Toast.LENGTH_LONG).show();
                }else {
                    if (objBuy == 1||objBuy == 0) {     //定期
                        if (mBetting_money.getText().toString().equals("") || mtouMoney == 0) {
                            tv_error_hint.setText("输入金额有误，请重新输入！");
                            shouyi_yuSuan.setVisibility(View.GONE);
                        } else {
                            if (mtouMoney % 100 == 0) {
                                shouyi_yuSuan.setVisibility(View.VISIBLE);
                                loginThisRequest("bidId", "1211");
                            }
                        }
                    } else {                //转让
                        if (add_and_sub.getNum() == 0) {
                            ToastManager.showShort(this, "输入的份数有误，请重新输入！");
                        } else {
                            loginThisRequest("investTransferId", "1212");
                        }
                    }
                }
                break;
            case R.id.rl_select_number:
                /**银行卡列表网络请求**/
                loginBankcardRequest();
                break;
            case R.id.select_voucher:
                /**选择抵用券**/
                if (isYuOrpay && user != null && user.getBank()==-1 && user.getBank_status().equals("2")) {
                     Toast.makeText(mContext, user.getBank_name()+"维护中，暂无法支付\n可在PC端以网银充值方式进行支付", Toast.LENGTH_LONG).show();
                }else {
                    if (objBuy == 1) {
                        bidType = "1";
                    } else {
                        buyAmount = add_and_sub.getNum() * buyBean.getPortionTransferAmount() + "";
                        bidType = "2";
                    }
                    //对于这段为啥又回传优惠券本身参数的问题，草，我都不想解释啥，就是为了打标签用的
                    Intent intent1 = new Intent(this, SelectVoucherList.class);
                    intent1.putExtra("buyAmount", buyAmount);
                    intent1.putExtra("bidType", bidType);
                    intent1.putExtra("itemId", itemId);                      //把itemid再返回回去，如果有值，就做上标记位
                    intent1.putExtra("itemAmount", itemAmount);
                    intent1.putExtra("type", type);
                    intent1.putExtra("rate", rate);
                    startActivityForResult(intent1, 1);
                }
                break;
            case R.id.fuwuxieyi:
                url = DataHandler.WEBURL + "/front/wa/serviceAgreement?pactId=11";
                bundle.putString("url", url);
                bundle.putString("title", "服务协议");
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.jiekuanxieyi:
                url = DataHandler.WEBURL + "/front/wa/serviceAgreement?pactId=13";
                bundle.putString("url", url);
                bundle.putString("title", "借款协议");
                intent.putExtras(bundle);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    /**
     * 此方法 判断 余额购买  还是  充值购买
     */
    public void selectBuyTyleRequest(double mtouMoney, double mBalance) {
        if (EditTextUtil.compareSize(mtouMoney, mBalance)) {
            if (user.getCurrUser().isSetPayPwd()) {
                PayPwdDilog mPayPwdDilog = new PayPwdDilog(this, null);
                mPayPwdDilog.setSuccessListener(new PayPwdDilog.SuccessListener() {
                    @Override
                    public void onPwdSuccess(String password) {
                        yuELoginRequest(password);
                    }
                });
            } else {
                Intent intent = new Intent();
                intent.putExtra("falg", 0);
                intent.setClass(this, TradePWD.class);        //跳转到支付密码设置页
                startActivity(intent);
            }
        } else {
            if (user.getBank() == -1) {         //绑过卡
                setPayPWD();
            } else {                            //未绑卡
                request();
                if (y == 1 && z == 1) {
                    setPayPWD();
                }
            }
        }
    }

    /**
     * 余额支付 网络请求
     */
    private void yuELoginRequest(String password) {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1307");
            parameters.put("id", user.getCurrUser().getSign());
            if (objBuy == 0 || objBuy ==1) {       //首投、定期
                parameters.put("buyAmount", mBetting_money.getText().toString());
                parameters.put("buyType", "2");
                parameters.put("bidId", Id);
            } else {                     //转让
                parameters.put("buyNum", add_and_sub.getNum() + "");
                parameters.put("buyType", "3");
                parameters.put("investTransferId", Id);
            }
            parameters.put("couponsId", itemId + "");
            parameters.put("dealPsword",DataHandler.encrypt3DES(password));
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon0, error);
            request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requen.add(request);
        }
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(BuyActivity.this, error);
        }
    };
    /**
     * 余额购买 返回结果
     */
    private Response.Listener<JSONObject> succeedRespon0 = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject jobj) {
            L.d("余额购买 返回结果" + jobj.toString());
            dg.dismiss();
            successBean = JSON.parseObject(jobj.toString(), FixedBuySuccessBean.class);
            if (successBean.getErrorCode() == -2) {   //逾期
                ToastManager.showShort(BuyActivity.this, successBean.getMsg());
            } else {
                if (successBean.getCode() == -1) {
                    successReturn();
                } else if (successBean.getCode() == -4){
                    ToastManager.showShort(BuyActivity.this, successBean.getMsg());
                }else {
                    failActivity();
                }
            }
        }
    };

    /**
     * 银行卡列表网络请求
     */
    private void loginBankcardRequest() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        final Map<String, String> parameters = DataHandler.getParameters("1302");
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedBankRespon, error);
        requen.add(request);
    }

    private Response.Listener<JSONObject> succeedBankRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            dg.dismiss();
            L.i("银行卡列表=============" + jobj.toString());
            BanksCardBean banksCardBean = JSON.parseObject(jobj.toString(), BanksCardBean.class);
            banksList = banksCardBean.getSupportBanks();
            if (banksList != null) {
                showBankcardDialog();
            }
        }
    };


    /**
     * 充值支付 网络请求
     */
    private void rechargeLoginRequest(String password) {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1301");
            parameters.put("id", user.getCurrUser().getSign());
            if (user.getBank() == -1) {
                parameters.put("card_no", user.getAccount());
                parameters.put("bankCode", user.getBank_code());
                parameters.put("single_amt", user.getSingle_amt() + "");
                parameters.put("day_amt", user.getDay_amt() + "");
                parameters.put("month_amt", user.getMonth_amt() + "");
            } else {
                parameters.put("card_no", tv_carnum.getText().toString());
                parameters.put("bankCode", mBankCode);
                parameters.put("single_amt", supportBanks.getSingle_amt() + "");
                parameters.put("day_amt", supportBanks.getDay_amt() + "");
                parameters.put("month_amt", supportBanks.getMonth_amt() + "");
            }
            if (objBuy == 1 || objBuy == 0) {
                BigDecimal b = new BigDecimal(mtouMoney - canUseingMoney - itemAmount);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                parameters.put("rechargeAmount", f1 + "");
                parameters.put("buyAmount", mtouMoney + "");
                parameters.put("rechargeType", "5");
                parameters.put("type", "2");
                parameters.put("bidId", Id);
            } else {
                BigDecimal b = new BigDecimal(transfer_mTouMoney - canUseingMoney - itemAmount);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                parameters.put("rechargeAmount", f1 + "");
                parameters.put("buyNum", add_and_sub.getNum() + "");
                parameters.put("rechargeType", "6");
                parameters.put("type", "3");
                parameters.put("investTransferId", Id);
            }
            parameters.put("couponsId", itemId + "");
            parameters.put("dealPsword",DataHandler.encrypt3DES(password));
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, rechargeSucceedRespon, error);
            request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requen.add(request);
        }
    }

    private Response.Listener<JSONObject> rechargeSucceedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i(jobj.toString());
            dg.dismiss();
            ActRechargeBean actRechargeBean = JSON.parseObject(jobj.toString(), ActRechargeBean.class);
            if (JSONManager.getError(jobj) == -1) {
                Jsonresult jsonresult = actRechargeBean.getJsonresult();
                if (jsonresult != null) {
                    JSONObject jsonresult0 = null;
                    String acct_name = strUTF8Name(jsonresult.getAcct_name());
                    try {
                        jsonresult0 = jobj.getJSONObject("jsonresult");
                        jsonresult0.put("acct_name", acct_name);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    L.d("跳转到连连支付平台");
                    MobileSecurePayer msp = new MobileSecurePayer();
                    boolean bRet = msp.pay(jsonresult0.toString(), mHandler,
                            Constants.RQF_PAY, BuyActivity.this, false);
                    Log.i(ActRechargeBinding.class.getSimpleName(),
                            String.valueOf(bRet));
                }
            } else {
                ToastManager.showShort(BuyActivity.this, actRechargeBean.getMsg());
            }
        }
    };
    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {
                    case Constants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        String retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");
                        String no_order = objContent.optString("no_order");
                        String result_pay = objContent.optString("result_pay");
                        String money_order = objContent.optString("money_order");
                        try {
                            objContent.put("ret_msg", "");
                            objContent.put("ret_code", "");
                            objContent.put("agreementno", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        L.d("连连支付返回json=================" + objContent.toString());
                        // TODO 先判断状态码，状态码为 成功或处理中 的需要 验签
                        if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
                            String resulPay = objContent.optString("result_pay");
                            if (Constants.RESULT_PAY_SUCCESS.equalsIgnoreCase(resulPay)) {
                                // TODO 支付成功后续处理
                                /**
                                 * 注意充值购买，是先充值 后购买  需要 验签
                                 * 所以需要再次请求网络，检查是否购买成功
                                 */
                                dg = UIManager.getLoadingDialog(BuyActivity.this);
                                dg.setCanceledOnTouchOutside(false);
                                dg.show();
                                final Map<String, String> parameters = DataHandler.getParameters("1308");
                                parameters.put("no_order", no_order);
                                parameters.put("result_pay", result_pay);
                                parameters.put("money_order", money_order);
                                parameters.put("res_data", objContent.toString());
                                /**
                                 * 延时1.5秒
                                 */
                                new Handler(new Handler.Callback() {
                                    @Override
                                    public boolean handleMessage(Message msg) {
                                        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
                                        request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                                        requen.add(request);
                                        return true;
                                    }
                                }).sendEmptyMessageDelayed(0, 2000);

                            } else {
                                ToastManager.showShort(BuyActivity.this, retMsg);
                            }
                        } else {
                            ToastManager.showShort(BuyActivity.this, retMsg);
                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            }
        };
    }

    /**
     * 这是连连充值成功后  服务后台验签 返回结果
     */
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("连连充值成功 验签结果==============" + jobj.toString());
            dg.dismiss();
            successBean = JSON.parseObject(jobj.toString(), FixedBuySuccessBean.class);
            if (JSONManager.getInt(jobj, "errorCode") == -2) {//逾期，
                ToastManager.showShort(BuyActivity.this, successBean.getMsg());
            } else {
                if (JSONManager.getString(jobj, "result").equals("SUCCESS")) {
                    successReturn();
                } else {
                    failActivity();
                }
            }
        }
    };


    /**
     * 购买成功后的跳转
     */
    public void successReturn() {
        double expectedReturns = successBean.getExpectedReturns();
        double buyAmount = successBean.getBuyAmount();
        String tranAward = successBean.getTransferFirstAward();
        String regularAward = successBean.getRegularFirstAward();
        Intent intent = new Intent(BuyActivity.this, FixedBuySuccessAct.class);
        Bundle bundle = new Bundle();
        bundle.putDouble("expectedReturns", expectedReturns);
        bundle.putDouble("buyAmount", buyAmount);
        if (objBuy == 1 || objBuy ==0) {
            bundle.putInt("objBuy", objBuy);
            if (regularAward != null) {
                int regularFirstAward = (int) Double.parseDouble(regularAward);
                bundle.putInt("regularFirstAward", regularFirstAward);
            } else {
                bundle.putInt("regularFirstAward", 0);
            }
        } else {
            bundle.putInt("objBuy", objBuy);
            if (tranAward != null) {
                int transferFirstAward = (int) Double.parseDouble(tranAward);
                bundle.putInt("transferFirstAward", transferFirstAward);
            } else {
                bundle.putInt("transferFirstAward", 0);
            }
        }
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 购买失败后的跳转
     * 失败页面取消，更改跳转到交易明细
     * 系统处理中
     */
    public void failActivity() {
//        startActivity(new Intent(BuyActivity.this, FixedBuyFailAct.class));
        UIManager.showSuccessDilog(BuyActivity.this,R.drawable.img_douing,1, "系统处理中，请稍后...", "查看交易记录", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(BuyActivity.this, ActTransactionDetailed.class));
                ActivityManager.getInstance().exitActivity();
            }
        });

    }

    /**
     * 只对定期输入框的监听
     */
    //监听
    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if ( objBuy == 0){
                mtouMoney = EditTextUtil.getDoubleEditText(mBetting_money);
                itemAmount = 0;itemId = 0;type = 0;rate = 0;
                all_buy_money0.setText(TextViewUtil.getSumLength(mtouMoney));
                if (mtouMoney % 100 == 0) {
                    //计算  预期收益
                    shouyi_yuSuan.setVisibility(View.VISIBLE);
                    tv_error_hint.setText("");
                    double yuqishouyi = calculateBenefits(mtouMoney, repaymentId, apr, periodUnit, period);
                    tv_shouyi.setText(TextViewUtil.getStringTwoLength(yuqishouyi));
                    long x = (long) mtouMoney;
                    tv_fenshu.setText((x / 100) + "");
                    buyAmount = mBetting_money.getText().toString();
                    if (!EditTextUtil.compareSize(mtouMoney, shengyuketou)) {
                        tv_error_hint.setText("输入金额不能大于剩余可投金额！");
                        shouyi_yuSuan.setVisibility(View.GONE);
                        mNoMoneyHint.setVisibility(View.GONE);
                        ll_nomoney_bank.setVisibility(View.GONE);
                        mMffirmBuy.setEnabled(false);
                        buyAmount = "0";
                    } else {
                        // 首投专享限额提示
                        if (!EditTextUtil.compareSize(mtouMoney, Double.parseDouble(xiane))){
                            tv_error_hint.setText("输入金额不能大于首投限额！");
                            shouyi_yuSuan.setVisibility(View.GONE);
                            mNoMoneyHint.setVisibility(View.GONE);
                            ll_nomoney_bank.setVisibility(View.GONE);
                            mMffirmBuy.setEnabled(false);
                        }else {
                            //  判断输入金额是否大于可用余额
                            compareMoney(mtouMoney, canUseingMoney);
                            tv_error_hint.setText("");
                            shouyi_yuSuan.setVisibility(View.VISIBLE);
                            mMffirmBuy.setEnabled(true);
                            buyAmount = mBetting_money.getText().toString();
                        }
                    }
                } else {
                    buyAmount = "0";
                    shouyi_yuSuan.setVisibility(View.GONE);
                    tv_error_hint.setText("输入金额应为100整数倍");
                    mMffirmBuy.setEnabled(false);
                    tv_fenshu.setText("0");
                    mNoMoneyHint.setVisibility(View.GONE);
                    ll_nomoney_bank.setVisibility(View.GONE);
                }
            }else if (objBuy == 1) {
                mtouMoney = EditTextUtil.getDoubleEditText(mBetting_money);
                // 兜券选择框的展示
                if (mtouMoney == 0) {
                    tv_quan_num.setTextColor(0xff666666);
                } else {
                    tv_quan_num.setTextColor(0xff6ED3D6);
                }
                itemAmount = 0;itemId = 0;type = 0;rate = 0;
                tv_quan_num.setText("选择兜券");

                all_buy_money0.setText(TextViewUtil.getSumLength(mtouMoney));
                if (mtouMoney % 100 == 0) {
                    //计算  预期收益
                    shouyi_yuSuan.setVisibility(View.VISIBLE);
                    tv_error_hint.setText("");
                    double yuqishouyi = calculateBenefits(mtouMoney, repaymentId, apr, periodUnit, period);
                    tv_shouyi.setText(TextViewUtil.getStringTwoLength(yuqishouyi));
                    long x = (long) mtouMoney;
                    tv_fenshu.setText((x / 100) + "");
                    buyAmount = mBetting_money.getText().toString();

                    //  判断输入金额是否大于可用余额
                    compareMoney(mtouMoney, canUseingMoney);
                    if (!EditTextUtil.compareSize(mtouMoney, shengyuketou)) {
                        tv_error_hint.setText("输入金额不能大于剩余可投金额！");
                        shouyi_yuSuan.setVisibility(View.GONE);
                        mNoMoneyHint.setVisibility(View.GONE);
                        ll_nomoney_bank.setVisibility(View.GONE);
                        mMffirmBuy.setEnabled(false);
                        buyAmount = "0";
                    } else {
                        tv_error_hint.setText("");
                        shouyi_yuSuan.setVisibility(View.VISIBLE);
                        mMffirmBuy.setEnabled(true);
                        buyAmount = mBetting_money.getText().toString();
                    }
                } else {
                    buyAmount = "0";
                    shouyi_yuSuan.setVisibility(View.GONE);
                    tv_error_hint.setText("输入金额应为100整数倍");
                    mMffirmBuy.setEnabled(false);
                    tv_fenshu.setText("0");
                    mNoMoneyHint.setVisibility(View.GONE);
                    ll_nomoney_bank.setVisibility(View.GONE);
                }
            } else {//转让状态下，避免和定期弹出银行卡绑定时出现冲突
                tv_error_hint.setText("");
                shouyi_yuSuan.setVisibility(View.VISIBLE);
            }
        }
    };

    /**
     * //判断  输入金额 是否大于 可用余额
     *
     * 显示银行卡
     * @param mtouMoney 输入金额
     * @param mBalance  可用余额
     */
    private void compareMoney(double mtouMoney, double mBalance) {
        if (EditTextUtil.compareSize(mtouMoney, mBalance)) {
            mNoMoneyHint.setVisibility(View.GONE);
            ll_nomoney_bank.setVisibility(View.GONE);
            isYuOrpay = false;
        } else {
            isYuOrpay = true;
            if (user.getBank() != -1) {
                tv_rexharge_money0.setText(TextViewUtil.getSumLength(mtouMoney - mBalance));
                mNoMoneyHint.setVisibility(View.VISIBLE);
                ll_nomoney_bank.setVisibility(View.GONE);
            } else {
                tv_rexharge_money.setText(TextViewUtil.getSumLength(mtouMoney - mBalance));
                ll_nomoney_bank.setVisibility(View.VISIBLE);
                mNoMoneyHint.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 收益计算方法
     */
    public double calculateBenefits(double buyAmount, int repaymentId, double apr, int periodUnit, int period) {
        if (periodUnit == 1) {
            return (buyAmount * apr * 0.01 * period / 365);
        } else {
            if (periodUnit == -1) {
                period = period * 12;
            }
            double monthApr = apr * 0.01 / 12;
            if (repaymentId == 1) {
                double monthPay = buyAmount * monthApr * Math.pow((1 + monthApr), period) / (Math.pow((1 + monthApr), period) - 1);
                return (monthPay * period - buyAmount);
            }
            if (repaymentId == 2 || repaymentId == 3) {
                double monthPay = buyAmount * monthApr;
                return (monthPay * period);
            }
        }
        return 0;
    }

    /**
     * URLdecode姓名转换成utf——8
     */
    public String strUTF8Name(String URLdecode) {
        String strUTF8 = null;
        try {
            strUTF8 = URLDecoder.decode(URLdecode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return strUTF8;
    }


    /**
     * 选择银行的小窗体PopupWindow
     */
    private void showBankcardDialog() {
        // 先把ListView创建出来
        lv = new ListView(this);
        lv.setBackgroundResource(R.drawable.listview_background);
        lv.setDividerHeight(1);
        // 隐藏滚动条
        lv.setVerticalScrollBarEnabled(false);
        adapter = new BankCartAdapter();
        L.i("banksList=============" + banksList.toString());
        adapter.setList(banksList);
        adapter.notifyDataSetChanged();
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        lv.setOnItemClickListener(this);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度（像素）
        int height;
        if (objBuy == 1||objBuy == 0) {
            height = metric.heightPixels - NewUtil.dip2px(this,343);
        } else {
            height = metric.heightPixels - NewUtil.dip2px(this,360);
        }
        pw = new PopupWindow(lv, width, height);
        // 设置点击外部 可以被关闭
        pw.setOutsideTouchable(true);
        pw.setBackgroundDrawable(new BitmapDrawable());
        // 指定popupWindow允许获得焦点
        pw.setFocusable(true);
        pw.showAtLocation(mBankcart, Gravity.BOTTOM, 0, 0);
    }

    class BankCartAdapter extends BaseAdapter {

        private List<SupportBanks> banksList;

        public void setList(List<SupportBanks> banksList) {
            this.banksList = banksList;
        }

        @Override
        public int getCount() {
            return banksList == null ? 0 : banksList.size();
        }

        @Override
        public Object getItem(int position) {
            return banksList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(BuyActivity.this, R.layout.bankcart_item, null);
                holder.tvNumber = (TextView) convertView.findViewById(R.id.tv_number);
                holder.bank_info = (TextView) convertView.findViewById(R.id.bank_info);
                holder.imgBankcard = (ImageView) convertView.findViewById(R.id.img_bankcard);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            SupportBanks supportBanks = banksList.get(position);
            if (banksList != null) {
                holder.tvNumber.setText(supportBanks.getBank_name());
                int x = new BankImgUtils().mBank(false, supportBanks.getBank_code());
                holder.imgBankcard.setImageResource(x);

                if (supportBanks.getBank_status().equals("2")) {
                    holder.bank_info.setText("该银行在维护中，暂不支持充值");
                } else {
                    holder.bank_info.setText("*单笔限额" + NumberFormat.getInstance().format(supportBanks.getSingle_amt() / 10000) +
                            "万元，每日限额" + NumberFormat.getInstance().format(supportBanks.getDay_amt() / 10000) + "万元");
                }
            }

            return convertView;
        }

        class ViewHolder {
            public TextView tvNumber;
            public ImageView imgBankcard;
            public TextView bank_info;
        }

    }

    /**
     * 取出银行名称数据, 显示在输入框中
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        supportBanks = banksList.get(position);
        if (supportBanks.getBank_status().equals("2")) {
            return;
        } else {
            mBank = supportBanks.getBank_name();
            mBankCode = supportBanks.getBank_code();
            pw.dismiss();
            /**
             * 选择好银行后的提示框 dialog
             */
            UIManager.showBankInfo(this, supportBanks, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    findViewById(R.id.rl_account_num).setVisibility(View.VISIBLE);
                    mBankcart.setText(mBank);
                    mBankcart.setTextColor(0xff333333);
                    tv_bank_hint.setText("*单笔限额" + NumberFormat.getInstance().format(supportBanks.getSingle_amt() / 10000) +
                            "万元，每日限额" + NumberFormat.getInstance().format(supportBanks.getDay_amt() / 10000) + "万元*");
                }
            });
        }
    }


    //判断输入框
    private void request() {
        String s = tv_carnum.getText().toString();
        if (s.equals("")) {
            tv_carnum.requestFocus();
            ToastManager.showShort(this, "请填写您的银行卡账号");
            y = 0;
            return;
        }
        y = 1;
        if (s.length() < 14) {
            ToastManager.showShort(this, "银行卡号格式不正确");
            z = 0;
            return;
        }
        z = 1;
    }
}